package tree.leetcode_129_medium;

import java.util.Deque;
import java.util.LinkedList;

public class DFSNonrecursion {
    public int sumNumbers(TreeNode root) {
        if(root == null){
            return 0;
        }
        Deque<TreeNode> nodeStack = new LinkedList<>();
        Deque<Integer> valueStack = new LinkedList<>();
        nodeStack.push(root);
        valueStack.push(root.val);
        int res = 0;
        while(!nodeStack.isEmpty()){
            TreeNode cur = nodeStack.pop();
            int value = valueStack.pop();
            if(cur.left == null && cur.right == null){
                res += value;
            }
            if(cur.right != null){
                nodeStack.push(cur.right);
                valueStack.push(value * 10 + cur.right.val);
            }
            if(cur.left != null){
                nodeStack.push(cur.left);
                valueStack.push(value * 10 + cur.left.val);
            }
        }
        return res;
    }
}
